import {
    dropMs,
    getState,
    getMsToCountDown,
    saveState,
    setStateMs,
    dropState,
    getCountDownPercents, incStateMs
} from "./state.js";
import {
    clearRankHighlight,
    clearTimer,
    defineTimeToLeftObject,
    highlightAllRankTill,
    onRankClick,
    startCountHint
} from "./common.js";

document.addEventListener('DOMContentLoaded', function() {
    console.log("SHOW POPUP");
    getState().then(state => {
        if(getMsToCountDown() > 0){
            startCountDown();
        }else{
            setStateMs(0).then(() => showMs(0))
        }
    })

    // document.querySelector(".rate").removeEventListener("mouseout", clearRankHighlight);
    // document.querySelector(".rate").addEventListener("mouseout", clearRankHighlight);
    document.querySelectorAll("[data-rank]").forEach(element => {
        element.removeEventListener('mouseover', highlightAllRankTill);
        element.addEventListener('mouseover', highlightAllRankTill);

        element.removeEventListener('click', onRankClick);
        element.addEventListener('click', onRankClick);
    })
});
let bgpage = undefined;
if (chrome.extension) {
    bgpage = chrome.extension.getBackgroundPage();
}
let isPointerDown = false;
let lastMs = 0;
let xDelta = 0;
let xPos = 0;

document.addEventListener('DOMContentLoaded', onMounted);

function resetScene(){
}

function getTimeToPositionDelta() {
    let trackReels = document.getElementById("track");
    let trackRect = trackReels.getBoundingClientRect();
    xDelta = trackRect.width/100;
    return xDelta;
}

function setAnchorsOnPositions() {
    let delta = getTimeToPositionDelta();
    let shift = -1;
    let nodes = document.getElementsByClassName("timeBtn");
    for(let i = 0; i<nodes.length; i++){
        let ms = nodes[i].getAttribute("data-ms");
        let targetId = nodes[i].getAttribute("data-target");
        document.getElementById(targetId).style.marginLeft = (ms / delta - shift) + "px";
    }
}

function startCountDown() {
    getState().then(state => {
        chrome.runtime.sendMessage("keep-alive");
        showMs(state.countTo);
        startCountHint();
        setTimeout(() => {
            if(!isPointerDown){
                startCountDown();
            }
        }, 200)
    })
}

function pushBG() {
    chrome.runtime.sendMessage('activate', (response) => {
        // console.log(response);
    });
}
function dragMarkerEvent(event) {
    event.preventDefault();
    if(isPointerDown){
        lastMs = xPositionToMs(event.layerX);
        showMs(lastMs);
    }
}

function xPositionToMs(x) {
    let trackReels = document.getElementById("trackReels");
    let trackRect = trackReels.getBoundingClientRect();
    let delta = getTimeToPositionDelta();
    let xMin = trackRect.left;
    let xMax = trackRect.width+trackRect.left;

    xPos = (x);
    if (xPos >= xMax) {
        xPos = xMax;
    } else if (xPos <= xMin) {
        xPos = 0;
    }
    return Math.floor(xPos * delta);
}

function updateTrackBar(percents) {
    let line = document.getElementById("line");
    let delta = getTimeToPositionDelta();
    let width = (percents * delta) - 2;
    if(width<=0){
        width = 0;
    }
    line.style.width = (width) + "px";
}


function updateTimeBar(ms){
    let digitE = document.getElementById("digitTime");
    let digitD = document.getElementById("digitDays");
    let cancelBtn = document.getElementById("cancel_btn");

    let date = new Date()
        date.setHours(0, 0, 0);
        date.setMilliseconds(ms);
    if(ms>0){
        cancelBtn.style.display="inline-flex";
    }
    let obj = defineTimeToLeftObject(ms);
    let d = obj.d;
    let h = obj.h;
    let m = obj.m;
    let s = obj.s;
    digitD.innerText = "";

    if(d>0){
        digitD.innerText = d + "d";
    }
    if(!d && !h && !m && !s){
        digitE.innerHTML = "--:--:--";
        return;
    }
    if (h < 10) {
        h = "0" + h;
    }
    if (m < 10) {
        m = "0" + m;
    }
    if (s < 10) {
        s = "0" + s;
    }
    digitE.innerText = h + ":" + m + ":" + s;
}

async function downPointer(event) {
    event.preventDefault();
    isPointerDown = true;
    lastMs = xPositionToMs(event.offsetX);
    getState().then(async state => {
        await saveState(state);
        startCountDown();
    })
}

async function dropPointer(event) {
    event.preventDefault();
    isPointerDown = false;
    let ms = xPositionToMs(event.offsetX);
    getState().then(async state => {
        if(ms <= 0){
            await dropState();
            return;
        }
        await setStateMs(ms);
        showMs(ms);
    })
}

async function leavePointer() {
    isPointerDown = false;
    startCountDown();
}

function showMs(ms){
    let percents = getCountDownPercents();
    updateTrackBar(percents);
    // moveMarkerTm(ms);
    updateTimeBar(ms);
}

function onMounted(){
    let cancel = document.querySelector('#cancel_btn');


    cancel.addEventListener('click', async (event) => {
        let cancelBtn = document.getElementById("cancel_btn");
        cancelBtn.style.display="none";
        await dropMs();
        resetScene();
        clearTimer();
        showMs(0);
        playActionSound();
    });

    let soundSettingsFunction = function (element, val) {
        element.classList.remove("on");
        getState().then(state => {
            state.projects.filter(row => row.id === val && row.on).forEach(row => {
                if(row.id === val){
                    setBgStyle(row);
                    element.classList.add("on");
                }
            })
        })
        element.addEventListener('mouseout', (event) => {
            event.target.classList.remove("hover");
        });

        element.addEventListener('mouseover', function (event) {
            let list = document.getElementsByClassName('timeBtn');
            for (let i = 0; i < list.length; i++) {
                list[i].classList.remove("hover");
            }
            event.target.classList.add("hover")
        });

        element.addEventListener('click', async (event) => {
            getState().then(async state => {
                let time_bar = document.getElementById("time_bar");
                let list = document.getElementsByClassName('snd');
                for (let i = 0; i < list.length; i++) {
                    list[i].classList.remove("on");
                }
                state.sound = val;

                await saveState(state);
                event.target.classList.add("on");
                time_bar.className = "snd_" + val;

                state.projects.forEach(row => {
                    row.on = false;
                    if(row.id === val){
                        row.on = true;
                        setBgStyle(row);
                    }
                })
                await saveState(state);
                playActionSound();
            })
        });
    }

    let setGoToTime = function (element) {
        element.addEventListener('click', async (event) => {
            let ms = event.target.getAttribute("data-ms");
            incStateMs(ms).then(async state => {
                showMs(state);
                await leavePointer(event);
                playActionSound();
            });
            // clickOnAnchor(event.target.id);
        });
    }

    soundSettingsFunction(document.getElementById('SndBlink'), 1);
    soundSettingsFunction(document.getElementById('SndFallout'), 2);
    soundSettingsFunction(document.getElementById('SndBigBan'), 3);
    soundSettingsFunction(document.getElementById('SndPokemon'), 4);
    soundSettingsFunction(document.getElementById('SndVader'), 5);
    soundSettingsFunction(document.getElementById('SndR2D2'), 6);


    let nodes = document.getElementsByClassName("timeBtn");
    for(let i = 0; i<nodes.length; i++) {
        setGoToTime(document.getElementById(nodes[i].getAttribute("id")));
    }
    setAnchorsOnPositions();
    getState().then(state => {
    });
}

function setIcon(url){
    let iconBlock = document
        .getElementById("time_bar")
        .getElementsByClassName("img")
        .item(0);
    iconBlock.style.backgroundImage = "url("+url+")";
}

function setBgStyle(row){
    document.querySelectorAll("#Theme").forEach(row => {
        document.head.removeChild(row);
    })
    chrome.action.setBadgeBackgroundColor({color: row.color});
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.id = 'Theme';
    link.type = 'text/css';
    link.href = 'css/theme_' + row.className + '.css';
    document.head.appendChild(link);

    // Append the link element to the head
    // document.head.appendChild(link);
    // setIcon(row.icon);
    let target = document.querySelector("body");
    target.setAttribute("class", row.className);
    setIcon(row.icon);
}

function playActionSound() {
    let audio = new Audio("./sound/general.wav");

    audio.play().then(play => {
        // console.log(play);
    });
}
